<template>
    <div class="main-container">
        <Scrollbar>
            <a-space direction="vertical" style="width: 100%;">
                <div style="height:100%;overflow:auto;width: 100% !important;padding: 10px 10px;">
                    <div
                        style="width: 40%;height:100%;display: inline-block;min-width: 380px;vertical-align: top;margin-right: 10px;">
                        <a-card :style="{ minWidth: '360px' }" title="菜单设置" hoverable>
                            <a-tree style="width:100%" block-node :data="data" :default-expand-all="true" ref="expandNode"
                                @select="selectTree">
                                <template #extra="nodeData">
                                    <IconPlus
                                        style="position: absolute; right: 8px; font-size: 15px; top: 10px; color: #3370ff;"
                                        @click="() => onIconClick(nodeData)" />
                                    <icon-minus
                                        style="position: absolute; right: 36px; font-size: 15px; top: 10px; color: red;"
                                        @click="() => onIconClick1(nodeData)" />
                                    <icon-edit
                                        style="position: absolute; right: 60px; font-size: 15px; top: 10px; color: yellowgreen;"
                                        @click="() => editHandler(nodeData)" />
                                    <icon-eye @click="() => setPermission(nodeData)"
                                        style="position: absolute; right: 84px; font-size: 15px; top: 10px; color: grey;" />
                                </template>
                            </a-tree>
                        </a-card>
                    </div>
                    <div style="width: 40%;height:100%;display: inline-block;min-width: 380px;">
                        <a-card :style="{ minWidth: '360px' }" title="菜单详情" hoverable>
                            <a-list>
                                <a-list-item>类型：{{ formData.type == 1 ? "菜单" : formData.type == 3 ? "页面" : "权限"
                                }}</a-list-item>
                                <a-list-item>菜单名称：{{ formData.menu }}</a-list-item>
                                <a-list-item>菜单图标：{{ formData.icon }}</a-list-item>
                                <a-list-item>菜单url：{{ formData.path }}</a-list-item>
                                <a-list-item>文件路径：{{ formData.component }}</a-list-item>
                                <a-list-item>权限值：{{ formData.qxz }}</a-list-item>
                                <a-list-item>排序：{{ formData.num }}</a-list-item>
                            </a-list>
                        </a-card>
                        <div class="my-tool-bar">
                            <Toolbar style="float: right;margin-top: 20px;" :items="['导入初始化', '导出']"
                                @IpInitialization="importHandler" @export="exports">
                            </Toolbar>
                        </div>
                    </div>
                </div>
            </a-space>
        </Scrollbar>
        <a-modal :visible="showAdd" :title="modalTitle" @ok="addhandler" @cancel="showAdd = false" @close="">
            <a-form ref="aform" :model="formData">
                <a-form-item label="类型">
                    <a-select popup-container="html"  v-model="formData.type">
                        <a-option :value="1">菜单</a-option>
                        <a-option :value="3">页面</a-option>
                        <a-option :value="4">权限</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="菜单名称">
                    <a-input v-model="formData.menu"></a-input>
                </a-form-item>
                <a-form-item label="菜单图标">
                    <a-input v-model="formData.icon"></a-input>
                </a-form-item>
                <a-form-item label="菜单url">
                    <a-input v-model="formData.path"></a-input>
                </a-form-item>
                <a-form-item label="文件路径">
                    <a-input v-model="formData.component"></a-input>
                </a-form-item>
                <a-form-item label="权限值">
                    <a-input v-model="formData.qxz"></a-input>
                </a-form-item>
                <a-form-item label="排序" v-if="modalTitle != '新增菜单'">
                    <a-input-number v-model="formData.num"></a-input-number>
                </a-form-item>
            </a-form>

        </a-modal>


        <a-modal :hide-cancel="true" ok-text="关 闭" @ok="permissionData.show = false" @cancel="permissionData.show = false"
            ref="perModal" title="设置权限" :visible="permissionData.show">
            <a-form size="small" layout="inline" :model="perinput">
                <a-form-item label="权限名">
                    <a-input v-model="perinput.ch" placeholder=""></a-input>
                </a-form-item>
                <a-form-item label="权限值">
                    <a-input v-model="perinput.en" placeholder=""></a-input>
                </a-form-item>
                <a-form-item>
                    <a-button @click="addRole">添加</a-button>
                </a-form-item>
                <a-scrollbar style="height:200px;overflow: auto;">

                    <a-tag size="large" @close="delRole(item.id + '')" color="#00b42a" bordered closable
                        v-for="item in permissionData.permissionList">

                        {{ item['name'] }}-{{ item['permissionValue'] }}
                    </a-tag>


                </a-scrollbar>

            </a-form>
        </a-modal>
    </div>
</template>
<script lang="ts">
import { del, get, post, put } from '@/api/http';
import { baseURL } from '@/api/axios.config.js'
import axios from 'axios';
import { Message, Modal } from '@arco-design/web-vue';

import { onMounted, reactive, ref, toRefs } from 'vue'
import { FormInstance } from '@arco-design/web-vue/es/form';

interface MenuItem {
    id: number,
    title: string,
    children: MenuItem[]
}

export default {
    name: 'MenuList',
    setup() {
        function onIconClick(nodeData: any) {
            for (const key in formData) {
                formData[key] = '';
            }
            pid = nodeData.key
            pageData.showAdd = true
            pageData.modalTitle = '新增菜单'
        }

        function onIconClick1(nodeData: any) {
            Modal.confirm({
                title: '系统提示',
                content: '是否删除此菜单及其子菜单？',
                onOk: () => {
                    axios.delete(baseURL + '/admin/acl/permission/remove/' + nodeData.key, {
                        headers: {
                            token: sessionStorage.getItem('USER-TOKEN-KEY')
                        }
                    }).then((result) => {
                        if (result.data.code === 200) {
                            Message.success('删除成功！')
                        } else {
                            Message.error('删除失败！')
                        }
                        doRefresh()
                    })

                }
            })

        }

        const aform = ref<FormInstance | null>(null)
        const exportData= ref([])
        const close = () => {
            aform.value?.resetFields()
        }

        const editHandler = (item: any) => {

            pageData.modalTitle = '修改菜单'
            EchoData(item.key, 1)
        }
        //回显数据
        function EchoData(id: any, num: any) {
            get({
                url: 'admin/acl/permission/PermissionId/' + id
            }).then(({ code, data }) => {
                if (code === 200) {
                    formData.num = data.permission.num
                    formData.component = data.permission.component
                    formData.menu = data.permission.name
                    formData.path = data.permission.path
                    formData.qxz = data.permission.permissionValue
                    formData.icon = data.permission.icon
                    formData.id = data.permission.id
                    pid = data.permission.pid
                    if (num == 1) {
                        pageData.showAdd = true
                    }


                } else {
                    Message.error('获取菜单数据失败')
                }


            })
        }

        let pid = 0
        const data = ref<MenuItem[]>([])
        onMounted(() => {
            doRefresh()
        })
        const pageData = reactive({
            showAdd: false,
            modalTitle: '新增菜单'
        })
        const formData:any = reactive({
            menu: '',
            path: '',
            component: '',
            qxz: '',
            type: 1,
            id: '',
            icon: "",
            num:null
        })
        const doRefresh = () => {
            get({ url: 'admin/acl/permission/indexAllPermission' })
                .then((result) => {
                    if (result.code === 200) {
                        exportData.value = result.data.children
                        data.value = result.data.children.map(function (o: any) {
                            let temp1 = { title: o.name, key: o.id }

                            temp1['children'] = Array.isArray(o.children) ? o.children.map((o1: any) => {

                                let temp2 = { title: o1.name, key: o1.id }
                                temp2['children'] = Array.isArray(o1.children) ? o1.children.map((o2: any) => {
                                    let temp3 = { title: o2.name, key: o2.id }
                                    temp3['children'] = Array.isArray(o2.children) ? o2.children.map((o3: any) => {
                                        let temp4 = { title: o3.name, key: o3.id }
                                        return temp4
                                    }) : []
                                    return temp3
                                }) : []
                                return temp2
                            }) : []
                            return temp1
                        })
                    }

                })
        }

        const addhandler = () => {
            if (pageData.modalTitle === '新增菜单') {
                post({
                    url: "admin/acl/permission/save",
                    data: {
                        "pid": pid,
                        "name": formData.menu,
                        "type": 1,
                        "permissionValue": formData.qxz,
                        "path": formData.path,
                        "component": formData.component,
                        "icon": formData.icon,
                    }
                }).then((result) => {
                    if (result.code === 200) {
                        Message.success('新增成功')
                    } else {
                        Message.error('新增失败')
                    }
                    doRefresh()
                    formData.component = ''
                    formData.icon = ''
                    formData.menu = ''
                    formData.path = ''
                    formData.qxz = ''
                    pageData.showAdd = false
                    formData.id = ''
                    pid = 0
                })
            } else {
                put({
                    url: "admin/acl/permission/update",
                    data: {
                        "pid": pid,
                        "name": formData.menu,
                        "type": 1,
                        "permissionValue": formData.qxz,
                        "path": formData.path,
                        "component": formData.component,
                        "icon": formData.icon,
                        id: formData.id,
                        "num":formData.num
                    }
                }).then((result) => {
                    if (result.code === 200) {
                        Message.success('修改成功')
                    } else {
                        Message.error('修改失败')

                    }
                    doRefresh()
                    formData.component = ''
                    formData.menu = ''
                    formData.path = ''
                    formData.qxz = ''
                    pageData.showAdd = false
                    formData.id = ''
                    pid = 0
                })
            }

        }
        const perinput = reactive({
            ch: '',
            en: ''
        })
        const permissionData = reactive<{ menuId: string, permissionList: MenuItem[], show: boolean }>({
            permissionList: [],
            show: false,
            menuId: ''
        })
        const setPermission = (nodeData: any) => {
            permissionData.menuId = nodeData.key
            get({
                url: 'admin/acl/permission/PermissionId/' + nodeData.key
            }).then(({ code, data }) => {
                if (code === 200) {

                    permissionData.show = true
                    permissionData.permissionList = data.permission.children.filter((o: MenuItem) => {
                        return o['type'] === 3
                    })
                } else {
                    Message.error('获取菜单数据失败')
                }


            })

        }
        const delRole = (delid: string) => {
            del({
                url: 'admin/acl/permission/remove/' + delid
            }).then(({ code, data }) => {
                if (code === 200) {
                    Message.success('删除成功')
                } else {
                    Message.success('删除失败')
                }
            })
        }
        const addRole = () => {
            post({
                url: 'admin/acl/permission/save',
                data: {
                    "pid": permissionData.menuId,
                    "name": perinput.ch,
                    "type": 3,
                    "permissionValue": perinput.en,
                }
            }).then(({ code, data }) => {
                if (code === 200) {
                    Message.success('成功')

                    get({
                        url: 'admin/acl/permission/PermissionId/' + permissionData.menuId
                    }).then(({ code, data }) => {
                        if (code === 200) {

                            permissionData.show = true
                            permissionData.permissionList = data.permission.children.filter((o: MenuItem) => {
                                return o['type'] === 3
                            })
                        } else {
                            Message.error('获取菜单数据失败')
                        }


                    })
                } else {
                    Message.error('失败')
                }
            })
        }
        const expandNode = ref()

        const selectTree = (selectedKeys: any, data: any) => {
            //获取现在展开的节点 判断现在点击的节点是否存在与这个展开节点的数组
            let openList = expandNode.value.getExpandedNodes()
            let isOpen = false;
            console.log(expandNode.value);

            openList.forEach(function (o: any) {
                if (o["key"] == selectedKeys[0]) {
                    isOpen = true;
                }
            })
            if (isOpen) {
                expandNode.value.expandNode(selectedKeys[0], false)
            } else {
                expandNode.value.expandNode(selectedKeys[0], true)
            }
            if (expandNode.value.computedSelectedKeys.length != 0) {
                EchoData(expandNode.value.computedSelectedKeys[0], 2)
            }
        }

        //导入
        const importHandler = () => {
            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept =
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！')
                    return
                }
                axios
                    .post(baseURL + '/admin/acl/permission/permissionImport', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            token: sessionStorage.getItem('USER-TOKEN-KEY'),
                        },
                    })
                    .then((result) => {
                        if (result.data['code'] === 200) {
                            Message.success('导入成功')
                        } else {
                            Message.error(result.data.message)
                        }
                    })
                    .finally(() => {
                        doRefresh()
                    })
            })
            inputEle.click()
        }
        //导出
        const exports = () => {
            //将表头拼接出来
            // let head =
            //     '<th>编号</th><th>所属上级</th><th>名称</th><th>类型</th><th>序号</th><th>权限值</th><th>访问路径</th><th>组件路径</th><th>图标</th><th>状态</th><th>层级</th><th>下级</th><th>是否选中</th>'
            // //拿到当前表格数据与勾选的行做筛选
            // console.log(data)
            // let body = ''
            // data.value.forEach(function (o: any) {
            //     body += '<tr><td>' + (o['id'] === undefined ? '' : o['id']) + '</td>'
            //     body += '<td>' + (o['pid'] === undefined ? '' : o['pid']) + '</td>'
            //     body += '<td>' + (o['name'] === undefined ? '' : o['name']) + '</td>'
            //     body += '<td>' + (o['type'] === undefined ? '' : o['type'] === 1 ? '菜单' : '按钮') + '</td>'
            //     body += '<td>' + (o['num'] === undefined ? '' : o['num']) + '</td>'
            //     body += '<td>' + (o['permissionValue'] === undefined ? '' : o['permissionValue']) + '</td>'
            //     body += '<td>' + (o['path'] === undefined ? '' : o['path']) + '</td>'
            //     body += '<td>' + (o['component'] === undefined ? '' : o['component']) + '</td>'
            //     body += '<td>' + (o['icon'] === undefined ? '' : o['icon']) + '</td>'
            //     body += '<td>' + (o['status'] === undefined ? '' : o['status'] === 0 ? '禁止' : '正常') + '</td>'
            //     body += '<td>' + (o['level'] === undefined ? '' : o['level']) + '</td>'
            //     body += '<td>' + (o['children'] === undefined ? '' : o['children']) + '</td>'
            //     body += '<td>' + (o['isSelect'] === undefined ? '' : o['isSelect']) + '</td>'
            //     body += '</tr>'
            // })
            //将表头拼接出来
            let head =
                '<th>一级菜单</th><th>二级菜单</th><th>三级菜单</th>'
            //拿到当前表格数据与勾选的行做筛选
            let body = ''
            console.log(exportData.value);
            
            exportData.value[0].children.forEach((frist:any)=>{
                
                if(frist.children?.length>0){
                frist.children.forEach((second:any)=>{
                    if(second.children?.length>0){
                        second.children.forEach((third:any)=>{
                            console.log(third);
                            
                        if (third.type!=3) {
                            body += '<tr><td>' + (frist['name'] === undefined ? '' : frist['name']) + '</td>'
                            body += '<td>' + (second['name'] === undefined ? '' : second['name']) + '</td>'
                            body += '<td>' + (third['name'] === undefined ? '' : third['name']) + '</td>'
                            body += '</tr>'
                        }
                    })
                    }else{
                        body += '<tr><td>' + (frist['name'] === undefined ? '' : frist['name']) + '</td>'
                        body += '<td>' + (second['name'] === undefined ? '' : second['name']) + '</td>'
                        body += '<td></td>'
                        body += '</tr>'
                    }
                       
                })
                }else{
                    body += '<tr><td>' + (frist['name'] === undefined ? '' : frist['name']) + '</td>'
                        body += '<td></td>'
                        body += '<td></td>'
                    body += '</tr>'
                }
            })

            tableToXlsx(head, '菜单管理', body)

        }
        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

            const a = document.createElement('a')
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
            a.download = filename
            a.click()
            document.removeChild(a)
        }
        return {
            addRole,
            delRole,
            perinput,
            setPermission,
            permissionData,
            editHandler,
            importHandler,
            exports,
            aform,
            close,
            onIconClick1,
            addhandler,
            formData,
            data,
            ...toRefs(pageData),
            onIconClick,
            expandNode,
            selectTree,
            exportData
        }
    }
}
</script>
<style scoped>
.main-container {
    background-color: white;
    height: 100%;
}
</style>